package cn.touna.jss.common.exception;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.domain.Response;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;

/**
 * 全局的参数校验异常处理
 * Created by wuwc on 2017/8/22.
 */
@ControllerAdvice
public class GlobalViolationControllerAdvice {

    @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Response handle(MethodArgumentNotValidException ex) {
        Response response = new Response();
        try {
            BindingResult result = ex.getBindingResult();
            FieldError error = result.getFieldError();
            String msg = processFieldError(error);
            response.fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED.getErrorCode(), msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private String processFieldError(FieldError error) {
        if (error != null) {
            return error.getDefaultMessage();
        }
        return null;
    }
}
